package com.yupi.yupicturebackend.controller;

import com.yupi.yupicturebackend.annotation.AuthCheck;
import com.yupi.yupicturebackend.common.BaseResponse;
import com.yupi.yupicturebackend.common.ResultUtils;
import com.yupi.yupicturebackend.constant.UserConstant;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.PictureEnhancementManager;
import com.yupi.yupicturebackend.model.dto.picture.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 图片增强功能控制器
 * 
 * <p>提供图片智能分析、水印处理、社交分享、批量处理、统计分析等扩展功能</p>
 * 
 * @author yupi
 */
@Slf4j
@RestController
@RequestMapping("/picture/enhancement")
public class PictureEnhancementController {

    @Resource
    private PictureEnhancementManager pictureEnhancementManager;

    /**
     * 智能分析图片
     *
     * @param imageUrl 图片URL
     * @return 分析结果
     */
    @GetMapping("/analyze")
    public BaseResponse<PictureAnalysisResult> analyzeImage(@RequestParam String imageUrl) {
        ThrowUtils.throwIf(imageUrl == null || imageUrl.trim().isEmpty(), ErrorCode.PARAMS_ERROR, "图片URL不能为空");
        
        PictureAnalysisResult result = pictureEnhancementManager.intelligentAnalysis(imageUrl);
        return ResultUtils.success(result);
    }

    /**
     * 添加智能水印
     *
     * @param request 水印请求
     * @return 处理结果
     */
    @PostMapping("/watermark")
    public BaseResponse<Map<String, Object>> addWatermark(@RequestBody WatermarkRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getImageUrl() == null || request.getImageUrl().trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "图片URL不能为空");
        
        Map<String, Object> result = pictureEnhancementManager.intelligentWatermark(
            request.getImageUrl(), 
            request.getWatermarkConfig(), 
            request.getCopyrightInfo()
        );
        
        return ResultUtils.success(result);
    }

    /**
     * 一键社交分享
     *
     * @param request 分享请求
     * @return 分享结果
     */
    @PostMapping("/share")
    public BaseResponse<Map<String, Object>> socialShare(@RequestBody SocialShareRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getShareConfig() == null, ErrorCode.PARAMS_ERROR, "分享配置不能为空");
        
        List<SocialPlatform> platforms = request.getPlatforms();
        if (platforms == null || platforms.isEmpty()) {
            // 默认分享到主流平台
            platforms = Arrays.asList(
                SocialPlatform.WEIBO, 
                SocialPlatform.WECHAT, 
                SocialPlatform.QQ,
                SocialPlatform.TWITTER
            );
        }
        
        Map<String, Object> result = pictureEnhancementManager.oneClickShare(request.getShareConfig(), platforms);
        return ResultUtils.success(result);
    }

    /**
     * 批量处理图片
     *
     * @param request 批量处理请求
     * @return 处理结果
     */
    @PostMapping("/batch-process")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Map<String, ProcessResult>> batchProcess(@RequestBody BatchProcessRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getImageUrls() == null || request.getImageUrls().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "图片URL列表不能为空");
        ThrowUtils.throwIf(request.getBatchConfig() == null, ErrorCode.PARAMS_ERROR, "批量处理配置不能为空");
        
        Map<String, ProcessResult> result = pictureEnhancementManager.intelligentBatchProcess(
            request.getImageUrls(), 
            request.getBatchConfig()
        );
        
        return ResultUtils.success(result);
    }

    /**
     * 综合统计分析
     *
     * @param request 分析请求
     * @return 分析报告
     */
    @PostMapping("/statistics")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Map<String, Object>> comprehensiveAnalysis(@RequestBody StatisticsRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        
        int days = request.getDays() != null ? request.getDays() : 30;
        
        Map<String, Object> result = pictureEnhancementManager.comprehensiveAnalysis(
            request.getPictureData(),
            request.getUserInteractions(),
            days
        );
        
        return ResultUtils.success(result);
    }

    /**
     * 图片相似度检测
     *
     * @param imageUrl1 图片1 URL
     * @param imageUrl2 图片2 URL
     * @return 相似度结果
     */
    @GetMapping("/similarity")
    public BaseResponse<PictureSimilarityResult> detectSimilarity(
            @RequestParam String imageUrl1, 
            @RequestParam String imageUrl2) {
        ThrowUtils.throwIf(imageUrl1 == null || imageUrl1.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "图片1 URL不能为空");
        ThrowUtils.throwIf(imageUrl2 == null || imageUrl2.trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "图片2 URL不能为空");
        
        PictureSimilarityResult result = pictureEnhancementManager.detectSimilarity(imageUrl1, imageUrl2);
        return ResultUtils.success(result);
    }

    /**
     * 盗图检测
     *
     * @param request 盗图检测请求
     * @return 检测结果
     */
    @PostMapping("/theft-detection")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Map<String, Boolean>> detectTheft(@RequestBody TheftDetectionRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getOriginalImageUrl() == null || request.getOriginalImageUrl().trim().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "原图URL不能为空");
        ThrowUtils.throwIf(request.getSuspiciousImageUrls() == null || request.getSuspiciousImageUrls().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "疑似盗图URL列表不能为空");
        
        Map<String, Boolean> result = pictureEnhancementManager.detectImageTheft(
            request.getOriginalImageUrl(), 
            request.getSuspiciousImageUrls()
        );
        
        return ResultUtils.success(result);
    }

    /**
     * 生成热度排行榜
     *
     * @param request 排行榜请求
     * @return 排行榜结果
     */
    @PostMapping("/hot-ranking")
    public BaseResponse<List<PictureStatistics>> generateHotRanking(@RequestBody HotRankingRequest request) {
        ThrowUtils.throwIf(request == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(request.getPictureStats() == null || request.getPictureStats().isEmpty(), 
            ErrorCode.PARAMS_ERROR, "图片统计数据不能为空");
        
        int topN = request.getTopN() != null ? request.getTopN() : 10;
        
        List<PictureStatistics> result = pictureEnhancementManager.generateHotRanking(
            request.getPictureStats(), 
            topN
        );
        
        return ResultUtils.success(result);
    }

    // ==================== 请求DTO类 ====================

    /**
     * 水印请求
     */
    public static class WatermarkRequest {
        private String imageUrl;
        private WatermarkConfig watermarkConfig;
        private CopyrightInfo copyrightInfo;
        
        // getters and setters
        public String getImageUrl() { return imageUrl; }
        public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; }
        public WatermarkConfig getWatermarkConfig() { return watermarkConfig; }
        public void setWatermarkConfig(WatermarkConfig watermarkConfig) { this.watermarkConfig = watermarkConfig; }
        public CopyrightInfo getCopyrightInfo() { return copyrightInfo; }
        public void setCopyrightInfo(CopyrightInfo copyrightInfo) { this.copyrightInfo = copyrightInfo; }
    }

    /**
     * 社交分享请求
     */
    public static class SocialShareRequest {
        private ShareConfig shareConfig;
        private List<SocialPlatform> platforms;
        
        // getters and setters
        public ShareConfig getShareConfig() { return shareConfig; }
        public void setShareConfig(ShareConfig shareConfig) { this.shareConfig = shareConfig; }
        public List<SocialPlatform> getPlatforms() { return platforms; }
        public void setPlatforms(List<SocialPlatform> platforms) { this.platforms = platforms; }
    }

    /**
     * 批量处理请求
     */
    public static class BatchProcessRequest {
        private List<String> imageUrls;
        private BatchProcessConfig batchConfig;
        
        // getters and setters
        public List<String> getImageUrls() { return imageUrls; }
        public void setImageUrls(List<String> imageUrls) { this.imageUrls = imageUrls; }
        public BatchProcessConfig getBatchConfig() { return batchConfig; }
        public void setBatchConfig(BatchProcessConfig batchConfig) { this.batchConfig = batchConfig; }
    }

    /**
     * 统计分析请求
     */
    public static class StatisticsRequest {
        private List<Map<String, Object>> pictureData;
        private List<Map<String, Object>> userInteractions;
        private Integer days;
        
        // getters and setters
        public List<Map<String, Object>> getPictureData() { return pictureData; }
        public void setPictureData(List<Map<String, Object>> pictureData) { this.pictureData = pictureData; }
        public List<Map<String, Object>> getUserInteractions() { return userInteractions; }
        public void setUserInteractions(List<Map<String, Object>> userInteractions) { this.userInteractions = userInteractions; }
        public Integer getDays() { return days; }
        public void setDays(Integer days) { this.days = days; }
    }

    /**
     * 盗图检测请求
     */
    public static class TheftDetectionRequest {
        private String originalImageUrl;
        private List<String> suspiciousImageUrls;
        
        // getters and setters
        public String getOriginalImageUrl() { return originalImageUrl; }
        public void setOriginalImageUrl(String originalImageUrl) { this.originalImageUrl = originalImageUrl; }
        public List<String> getSuspiciousImageUrls() { return suspiciousImageUrls; }
        public void setSuspiciousImageUrls(List<String> suspiciousImageUrls) { this.suspiciousImageUrls = suspiciousImageUrls; }
    }

    /**
     * 热度排行榜请求
     */
    public static class HotRankingRequest {
        private List<PictureStatistics> pictureStats;
        private Integer topN;
        
        // getters and setters
        public List<PictureStatistics> getPictureStats() { return pictureStats; }
        public void setPictureStats(List<PictureStatistics> pictureStats) { this.pictureStats = pictureStats; }
        public Integer getTopN() { return topN; }
        public void setTopN(Integer topN) { this.topN = topN; }
    }
}
